package com.pars.xmlFiles;

import java.util.*;

import javax.xml.parsers.*;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.commun.Param;
import com.object.Mosque;

public class DomFeedParser extends BaseFeedParser {

	public DomFeedParser(String feedUrl) {
		super(feedUrl);
	}

	public List<Mosque> parse() {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		List<Mosque> messages = new ArrayList<Mosque>();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse(this.getInputStream());
			Element root = dom.getDocumentElement();
			NodeList items = root.getElementsByTagName(Param.MOSQUAI);

			for (int i = 0; i < items.getLength(); i++) {
				Mosque message = new Mosque();
				Node item = items.item(i);
				NodeList properties = item.getChildNodes();
				for (int j = 0; j < properties.getLength(); j++) {
					Node property = properties.item(j);
					String name = property.getNodeName();
					if (name.equalsIgnoreCase(Param.NOM)) {
						message.setNom(property.getFirstChild().getNodeValue());
					} else if (name.equalsIgnoreCase(Param.INFO)) {
						message
								.setInfo(property.getFirstChild()
										.getNodeValue());
					} else if (name.equalsIgnoreCase(Param.ID)) {
						message.setId(Integer.parseInt(property.getFirstChild()
								.getNodeValue()));
					} else if (name.equalsIgnoreCase(Param.LONGITUDE)) {
						message.setLongitude(Float.parseFloat(property
								.getFirstChild().getNodeValue()));
					} else if (name.equalsIgnoreCase(Param.LATITUDE)) {
						message.setLatitude(Float.parseFloat(property
								.getFirstChild().getNodeValue()));
					} else if (name.equalsIgnoreCase(Param.HAVE_PICTURE)) {
						message.setHavePicture(Boolean.valueOf(property
								.getFirstChild().getNodeValue()));
					} else if (name.equalsIgnoreCase(Param.PICTURE)) {
						message.setPictureName(property.getFirstChild()
								.getNodeValue());
					}
				}
				messages.add(message);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return messages;
	}
}